package com.hundsun.yr.universal.library.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.common.CPResourceUtil;
import com.hundsun.yr.universal.library.common.DensityUtils;
import com.hundsun.yr.universal.library.utils.ViewUtils;
import com.hundsun.yr.universal.library.widget.HSEditText.HSInputType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @Title: HSPassedwordEditText.java
 * @Description: 密码输入框
 * @date 2015-12-1 上午10:18:50
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 * @version V1.0
 */
@SuppressLint("ClickableViewAccessibility")
public class HSPassedwordEditText extends LinearLayout implements OnClickListener {
	/**
	 * 右边按钮的引用（默认为眼睛按钮）
	 */
	private Drawable mEyeDrawable;
	/**
	 * 右边按钮的引用（默认为眼睛按钮）按下效果
	 */
	private Drawable mEyeDrawable_p;

	/**
	 * 右边按钮的引用（默认为眼睛按钮）
	 */
	private Drawable mEyeDrawable_n;

	private boolean isChecked = false;

	/**
	 * HSEditText右边按钮的引用（默认为删除按钮）
	 */
	protected Drawable mRightDrawable;
	/**
	 * HSEditText左边图标的引用
	 */
	private Drawable mLeftDrawable;
	/**
	 * 缩放系数
	 */
	private float scal = 0;

	private HSEditText mHsEditText;

	private ImageView mEyeImageView;

	/**
	 * HSEditText hint文字颜色
	 */
	private int hintTextColor = -1;

	private CharSequence mQueryHint;
	/**
	 * HSEditText 文字颜色
	 */
	private int textColor = -1;

	/**
	 * HSEditText 文字大小
	 */
	private int textSize = 0;

	public int inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
	/**眼睛按下图片**/
	private int eye_p=0;
	/**眼睛图片 **/
	private int eye_n=0;

	public HSPassedwordEditText(Context context) {
		this(context, null);
	}

	public HSPassedwordEditText(Context context, AttributeSet attrs) {
		// 这里构造方法也很重要，不加这个很多属性不能再XML里面定义
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public HSPassedwordEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, attrs);
	}

	@SuppressWarnings("deprecation")
	private void init(final Context context, AttributeSet attrs) {

		setOrientation(LinearLayout.HORIZONTAL);
		setGravity(Gravity.CENTER_VERTICAL);

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
		mHsEditText = new HSEditText(getContext());
		mHsEditText.setBackgroundColor(Color.TRANSPARENT);
		mHsEditText.setInputType(inputType);
		final String digists = "0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-/:;()$&@.,?!'[]{}#%^*+=_\\|~<>￥。";
		mHsEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

				String editable = getText().toString();
				String str = stringFilter(editable.toString());
				if(!editable.equals(str)){
					setText(str);
					//设置新的光标所在位置
					mHsEditText.setSelection(str.length());
				}
//				if (!s.toString().matches("[a-zA-Z0-9]+-/:;()$&@.,?!'#%^*+=_\\|~<>￥.")) {
//					setText("");
//				}

//				if (s.toString().matches("[\u4e00-\u9fa5]+")) {
//					mHsEditText.setText("");
//				} else if (count-before >= 2) {//表情符号的字符长度最小为2
//					CharSequence input = s.subSequence(start+before, start + count);
//					if (containsEmoji(input.toString())) {
//						mHsEditText.setText("");
//						CharSequence text = getText();
//					}
//				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});


		eye_p=CPResourceUtil.getDrawableId(context, "eye_show");
		eye_n=CPResourceUtil.getDrawableId(context, "eye_close");

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HSPasswordEditText);
		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_hintTextColor)) {
			hintTextColor = a.getColor(R.styleable.HSPasswordEditText_hs_pwdet_hintTextColor, -1);
			mHsEditText.setQueryHintColor(hintTextColor);
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_hint)) {
			mQueryHint = a.getString(R.styleable.HSPasswordEditText_hs_pwdet_hint);
			mHsEditText.setQueryHint(mQueryHint);
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_textColor)) {
			textColor = a.getColor(R.styleable.HSPasswordEditText_hs_pwdet_textColor, -1);
			if (textColor != -1) {
				mHsEditText.setTextColor(textColor);
			}
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_textSize)) {
			textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, a.getDimension(R.styleable.HSPasswordEditText_hs_pwdet_textSize, 0), getResources().getDisplayMetrics());
			if (textSize != 0) {
				mHsEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
			}
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_left_drawable)) {
			mLeftDrawable = a.getDrawable(R.styleable.HSPasswordEditText_hs_pwdet_left_drawable);
			mHsEditText.setLeftDrawable(mLeftDrawable);
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_right_drawable)) {
			mRightDrawable = a.getDrawable(R.styleable.HSPasswordEditText_hs_pwdet_right_drawable);
			mHsEditText.setRightDrawable(mRightDrawable);
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_eye_ischecked)) {
			isChecked = a.getBoolean(R.styleable.HSPasswordEditText_hs_pwdet_eye_ischecked, false);
		}
		// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_eye_drawable_p)) {
			mEyeDrawable_p = a.getDrawable(R.styleable.HSPasswordEditText_hs_pwdet_eye_drawable_p);
		} else {
			if (mEyeDrawable_p == null) {
				mEyeDrawable_p = getResources().getDrawable(eye_p);
			}
		}

		// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_eye_drawable_n)) {
			mEyeDrawable_n = a.getDrawable(R.styleable.HSPasswordEditText_hs_pwdet_eye_drawable_n);
		} else {
			if (mEyeDrawable_n == null) {
				mEyeDrawable_n = getResources().getDrawable(eye_n);
			}
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_hsInputtype)) {
			int hsInputtype = a.getInt(R.styleable.HSPasswordEditText_hs_pwdet_hsInputtype, 0);
			mHsEditText.setHSInputType(hsInputtype);
		}

		if (a.hasValue(R.styleable.HSPasswordEditText_hs_pwdet_maxLength)) {
			int maxLength = a.getInt(R.styleable.HSPasswordEditText_hs_pwdet_maxLength, 100);
			mHsEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) });
		}

		setEyeEyeDrawable();

		a.recycle();
		mHsEditText.setCustomPadding(0, 0, DensityUtils.dp2px(context, 4), 0);
		mHsEditText.setMaxLines(1);
		addView(mHsEditText, params);

		mEyeImageView = new ImageView(getContext());
		mEyeImageView.setOnClickListener(this);
		addView(mEyeImageView);

	}

	/**
	 * 设置最大字符数
	 * 
	 * @param maxLength
	 */
	public void setMaxLength(int maxLength) {
		mHsEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength) });
	}

	/**
	 * 设置眼睛图片
	 */
	private void setEyeEyeDrawable() {
		// if(isChecked){
		// mEyeDrawable=mEyeDrawable_p;
		// }else{
		// mEyeDrawable=mEyeDrawable_n;
		// }
		mEyeDrawable = isChecked ? mEyeDrawable_p : mEyeDrawable_n;
	}

	/**
	 * 获取HSEditText对象
	 * 
	 * @return
	 */
	public HSEditText getHSEditText() {
		if (mHsEditText == null) {
			throw new IllegalArgumentException("You must create a new HSEditText");
		}

		return mHsEditText;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
		// TODO Auto-generated method stub
		super.onLayout(changed, left, top, right, bottom);


		if (mEyeImageView != null && mEyeDrawable != null) {
			if (scal == 0) {
//				scal = (float) ((0.6 * getMeasuredHeight()) / mEyeDrawable.getIntrinsicWidth());
//				mEyeImageView.getLayoutParams().width = mHsEditText.getRightWidth() == 0 ? (int) (mEyeDrawable.getIntrinsicWidth() * scal) : mHsEditText.getRightWidth();
//				mEyeImageView.getLayoutParams().height = mHsEditText.getRightHeight() == 0 ? (int) (mEyeDrawable.getIntrinsicHeight() * scal) : mHsEditText.getRightHeight();
//				mEyeDrawable.setBounds(0, 0, mHsEditText.getRightWidth() == 0 ? (int) (mEyeDrawable.getIntrinsicWidth() * scal) : mHsEditText.getRightWidth(),
//						mHsEditText.getRightHeight() == 0 ? (int) (mEyeDrawable.getIntrinsicHeight() * scal) : mHsEditText.getRightHeight());
//				mEyeImageView.setImageDrawable(mEyeDrawable);
				
				if(DensityUtils.dp2px(getContext(), 20)<getMeasuredHeight()){
					if(DensityUtils.dp2px(getContext(), 20)<mEyeDrawable.getIntrinsicHeight()){
						scal=(float)DensityUtils.dp2px(getContext(), 20)/mEyeDrawable.getIntrinsicHeight();
					}else{
						scal=(float) (0.4*getMeasuredHeight())/mEyeDrawable.getIntrinsicHeight();
					}
				}else{
					scal=(float) (0.4*getMeasuredHeight())/mEyeDrawable.getIntrinsicHeight();
				}
				int rightWidth=(int)(mEyeDrawable.getIntrinsicWidth());
				int rightHeight=(int)(mEyeDrawable.getIntrinsicHeight());
				mEyeImageView.getLayoutParams().width=rightWidth;
				mEyeImageView.getLayoutParams().height=rightHeight;
				mEyeDrawable.setBounds(0, 0,rightWidth, rightHeight);
				mEyeImageView.setImageDrawable(mEyeDrawable);
				
				invalidate();
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		if (inputType == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
			inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
			isChecked = true;
		} else {
			inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
			isChecked = false;
		}
		setEyeEyeDrawable();
		mEyeImageView.setImageDrawable(mEyeDrawable);
		mHsEditText.setInputType(inputType);
		ViewUtils.moveCursor(mHsEditText);

	}

	/**
	 * 获取EditText的值
	 * 
	 * @return
	 */
	public String getText() {

		if (TextUtils.isEmpty(mHsEditText.getText())) {
			return "";
		}

		if (mHsEditText.getHSInputType() == HSInputType.PHONE) {
			return mHsEditText.getPhone();
		} else if (mHsEditText.getHSInputType() == HSInputType.BANKCARD) {
			return mHsEditText.getBank();
		}
		return mHsEditText.getText().toString();
	}

	/**
	 * 设置文本
	 * 
	 * @param res
	 */
	public void setText(int res) {
		mHsEditText.setText(res);
	}

	/**
	 * 设置文本
	 * 
	 * @param text
	 */
	public void setText(String text) {
		mHsEditText.setText(text);
	}

	/**
	 * 设置初始值
	 * 
	 * @param content
	 */
	public void setFirstText(String content) {
		mHsEditText.division(content, 0);
	}

	/**
	 * 检测是否有emoji表情
	 *
	 * @param source
	 * @return
	 */
	public static boolean containsEmoji(String source) {
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
				return true;
			}
		}
		return false;
	}

	/**
	 * 判断是否是Emoji
	 *
	 * @param codePoint 比较的单个字符
	 * @return
	 */
	private static boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
				(codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
				((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
				&& (codePoint <= 0x10FFFF));
	}

	public static String stringFilter(String str)throws PatternSyntaxException {
		// 只允许字母、数字和汉字
		String   regEx  =  "[^a-zA-Z0-9`~!@#$%^&*()+-=|{}':;',\\\\[\\\\].<>/?~@#%&*+|{}]";
		Pattern   p   =   Pattern.compile(regEx);
		Matcher m   =   p.matcher(str);
		return   m.replaceAll("").trim();
	}
}
